function [ nmi ] = nmi_fun( clu_assignment1,clu_assignment2 )
%NMI: Compute the normalized mutual information of the two input partitions.
%   clu_assignment1: cluster 1
%   clu_assignment2: cluster 2

% decode the genetic representation.
clu_assignment1 = decode(clu_assignment1);
clu_assignment2 = decode(clu_assignment2);

nodes_sum = length(clu_assignment1);
clu_num1 = max(clu_assignment1);
clu_num2 = max(clu_assignment2);
conf_mat = zeros(clu_num1,clu_num2);    % confusion matrix.
for i = 1:clu_num1
    for j = 1:clu_num2
        index1 = find(clu_assignment1 == i);
        index2 = find(clu_assignment2 == j);
        num1 = length(index1);          % the number of nodes in community i.
        num2 = length(index2);          % the number of nodes in community j.
        numtemp = 0;
        for m = 1:num1
            for n = 1:num2
                if index1(m) == index2(n)
                    numtemp = numtemp + 1;
                end
            end
        end       
        conf_mat(i,j) = numtemp;
    end
end

% the numerator part
nmi_numerator = 0;
for i = 1:clu_num1
    for j = 1:clu_num2
        if conf_mat(i,j) ~= 0
            nmi_numerator = nmi_numerator + ...
            conf_mat(i,j) * ...
            log10( (conf_mat(i,j)*nodes_sum) / (sum(conf_mat(i,:))*sum(conf_mat(:,j))) );
        end       
    end
end
nmi_numerator = -2 * nmi_numerator;

%the denominator part
nmi_denominator1 = 0;
nmi_denominator2 = 0;
for i = 1:clu_num1
    nmi_denominator1 = nmi_denominator1 + sum(conf_mat(i,:)) * log10( sum(conf_mat(i,:)) / nodes_sum );
end
for j = 1:clu_num2
    nmi_denominator2 = nmi_denominator2 + sum(conf_mat(:,j)) * log10( sum(conf_mat(:,j)) / nodes_sum );
end
nmi_denominator = nmi_denominator1 + nmi_denominator2;

% final NMI
nmi = nmi_numerator/nmi_denominator;

end

